#coding=utf-8
#Boa:Frame:FramePro

import sys
import wx
import wx.lib.buttons
import wx.grid

import product
from product import *
from ctrlAider import *

from DlgProGX import *
from config import *
from PopupWinCategory import *
from DlgCategory import *
from DlgKeyword import *
from DlgEditPro import *
from MyListCtrl import MyProductListCtrl

def create(parent):
    return FramePro(parent)

[wxID_FRAMEPRO, wxID_FRAMEPROBTNABOLISH, wxID_FRAMEPROBTNADDLABEL, 
 wxID_FRAMEPROBTNCANCEL, wxID_FRAMEPROBTNCATEGORY, wxID_FRAMEPROBTNCONFIRM, 
 wxID_FRAMEPROBTNDEL, wxID_FRAMEPROBTNKEYWORD, wxID_FRAMEPROBTNSAVE, 
 wxID_FRAMEPROBTNSEARCH, wxID_FRAMEPROBTNSEARCHCATEGORY, 
 wxID_FRAMEPROBTNSEARCHKEYWORD, wxID_FRAMEPROCHECKONUSE, 
 wxID_FRAMEPROGRIDUNIT, wxID_FRAMEPROLISTCTRL_PROSEL, wxID_FRAMEPRONBPROINFO, 
 wxID_FRAMEPRONOTEBOOK1, wxID_FRAMEPROPANEL1, wxID_FRAMEPROPANEL2, 
 wxID_FRAMEPROPANEL_PROEDITOR, wxID_FRAMEPROPANEL_PROLIST, 
 wxID_FRAMEPROSTATICBOX_PROSEL, wxID_FRAMEPROSTATICBOX_UNIT, 
 wxID_FRAMEPROSTATICTEXT1, wxID_FRAMEPROTBRAND, wxID_FRAMEPROTCATEGORY, 
 wxID_FRAMEPROTCBRAND, wxID_FRAMEPROTCID, wxID_FRAMEPROTCKEYWORD, 
 wxID_FRAMEPROTCMEMO, wxID_FRAMEPROTCNAME, wxID_FRAMEPROTCSEARCH, 
 wxID_FRAMEPROTCSIMCODE, wxID_FRAMEPROTCSPEC, wxID_FRAMEPROTCTYPE, 
 wxID_FRAMEPROTID, wxID_FRAMEPROTKEYWORD, wxID_FRAMEPROTMEMO, 
 wxID_FRAMEPROTNAME, wxID_FRAMEPROTSEARCH, wxID_FRAMEPROTSIMCODE, 
 wxID_FRAMEPROTSPEC, wxID_FRAMEPROTTYPE, 
] = [wx.NewId() for _init_ctrls in range(43)]

class FramePro(wx.Frame):

    def _init_coll_notebook1_Pages(self, parent):
        # generated method, don't edit

        parent.AddPage(imageId=-1, page=self.panel1, select=True,
              text=u'\u5546\u54c1\u5217\u8868')
        parent.AddPage(imageId=-1, page=self.panel2, select=False,
              text=u'\u91c7\u8d2d\u5386\u53f2')

    def _init_coll_NBProInfo_Pages(self, parent):
        # generated method, don't edit

        parent.AddPage(imageId=-1, page=self.panel_proList, select=True,
              text=u'\u4ea7\u54c1\u5217\u8868')
        parent.AddPage(imageId=-1, page=self.panel_proEditor, select=False,
              text=u'\u4ea7\u54c1\u7f16\u8f91')

    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAMEPRO, name=u'FramePro', parent=prnt,
              pos=wx.Point(2, 118), size=wx.Size(1278, 652),
              style=wx.DEFAULT_FRAME_STYLE, title=u'\u4ea7\u54c1\u4fe1\u606f')
        self.SetClientSize(wx.Size(1270, 618))
        self.Center(wx.BOTH)
        self.SetBackgroundColour(wx.Colour(128, 128, 128))
        self.SetToolTipString(u'FramePro')
        self.Bind(wx.EVT_CLOSE, self.OnFrameProClose)
        self.Bind(wx.EVT_PAINT, self.OnFrameProPaint)

        self.NBProInfo = wx.Notebook(id=wxID_FRAMEPRONBPROINFO,
              name=u'NBProInfo', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(1270, 618), style=0)
        self.NBProInfo.SetLabel(u'')

        self.panel_proEditor = wx.Panel(id=wxID_FRAMEPROPANEL_PROEDITOR,
              name=u'panel_proEditor', parent=self.NBProInfo, pos=wx.Point(0,
              0), size=wx.Size(1262, 591), style=wx.TAB_TRAVERSAL)
        self.panel_proEditor.SetBackgroundColour(wx.Colour(128, 128, 128))
        self.panel_proEditor.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, u'\u6977\u4f53_GB2312'))

        self.panel_proList = wx.Panel(id=wxID_FRAMEPROPANEL_PROLIST,
              name=u'panel_proList', parent=self.NBProInfo, pos=wx.Point(0, 0),
              size=wx.Size(1262, 591), style=wx.TAB_TRAVERSAL)
        self.panel_proList.SetBackgroundColour(wx.Colour(128, 128, 128))
        self.panel_proList.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, u'\u6977\u4f53_GB2312'))

        self.TCSimCode = wx.TextCtrl(id=wxID_FRAMEPROTCSIMCODE,
              name=u'TCSimCode', parent=self.panel_proEditor, pos=wx.Point(440,
              48), size=wx.Size(100, 22), style=0, value=u'')

        self.TSimCode = wx.StaticText(id=wxID_FRAMEPROTSIMCODE,
              label=u'\u7b80\u7801\uff1a', name=u'TSimCode',
              parent=self.panel_proEditor, pos=wx.Point(360, 48),
              size=wx.Size(56, 14), style=0)

        self.CheckOnUse = wx.CheckBox(id=wxID_FRAMEPROCHECKONUSE,
              label=u'\u542f\u7528', name=u'CheckOnUse',
              parent=self.panel_proEditor, pos=wx.Point(680, 48),
              size=wx.Size(79, 14), style=0)
        self.CheckOnUse.SetValue(True)

        self.TType = wx.StaticText(id=wxID_FRAMEPROTTYPE,
              label=u'\u7c7b\u578b\uff1a', name=u'TType',
              parent=self.panel_proEditor, pos=wx.Point(360, 96),
              size=wx.Size(64, 14), style=0)

        self.TCID = wx.TextCtrl(id=wxID_FRAMEPROTCID, name=u'TCID',
              parent=self.panel_proEditor, pos=wx.Point(160, 96),
              size=wx.Size(100, 22), style=0, value=u'')
        self.TCID.SetEditable(False)

        self.TID = wx.StaticText(id=wxID_FRAMEPROTID,
              label=u'\u7f16\u53f7\uff1a', name=u'TID',
              parent=self.panel_proEditor, pos=wx.Point(88, 96),
              size=wx.Size(56, 14), style=0)

        self.staticBox_unit = wx.StaticBox(id=wxID_FRAMEPROSTATICBOX_UNIT,
              label=u'\u5355\u4f4d', name=u'staticBox_unit',
              parent=self.panel_proEditor, pos=wx.Point(96, 248),
              size=wx.Size(648, 160), style=0)

        self.gridUnit = wx.grid.Grid(id=wxID_FRAMEPROGRIDUNIT, name=u'gridUnit',
              parent=self.panel_proEditor, pos=wx.Point(136, 272),
              size=wx.Size(576, 120), style=0)
        self.gridUnit.SetDefaultColSize(70)
        self.gridUnit.SetDefaultRowSize(25)
        self.gridUnit.SetRowLabelSize(15)
        self.gridUnit.SetColLabelSize(25)

        self.TCMemo = wx.TextCtrl(id=wxID_FRAMEPROTCMEMO, name=u'TCMemo',
              parent=self.panel_proEditor, pos=wx.Point(192, 432),
              size=wx.Size(552, 48), style=wx.HSCROLL | wx.TE_MULTILINE,
              value=u'')

        self.TMemo = wx.StaticText(id=wxID_FRAMEPROTMEMO,
              label=u'\u4ea7\u54c1\u5907\u6ce8\uff1a', name=u'TMemo',
              parent=self.panel_proEditor, pos=wx.Point(96, 432),
              size=wx.Size(96, 14), style=0)

        self.TName = wx.StaticText(id=wxID_FRAMEPROTNAME,
              label=u'\u540d\u79f0\uff1a', name=u'TName',
              parent=self.panel_proEditor, pos=wx.Point(88, 48),
              size=wx.Size(56, 14), style=0)

        self.TCName = wx.TextCtrl(id=wxID_FRAMEPROTCNAME, name=u'TCName',
              parent=self.panel_proEditor, pos=wx.Point(160, 48),
              size=wx.Size(100, 22), style=0, value=u'')

        self.btnSave = wx.Button(id=wxID_FRAMEPROBTNSAVE, label=u'\u4fdd\u5b58',
              name=u'btnSave', parent=self.panel_proEditor, pos=wx.Point(832,
              416), size=wx.Size(75, 24), style=0)
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnBtnSaveButton,
              id=wxID_FRAMEPROBTNSAVE)

        self.btnCancel = wx.Button(id=wxID_FRAMEPROBTNCANCEL,
              label=u'\u53d6\u6d88', name=u'btnCancel',
              parent=self.panel_proEditor, pos=wx.Point(832, 472),
              size=wx.Size(75, 24), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_FRAMEPROBTNCANCEL)

        self.TSpec = wx.StaticText(id=wxID_FRAMEPROTSPEC,
              label=u'\u89c4\u683c\uff1a', name=u'TSpec',
              parent=self.panel_proEditor, pos=wx.Point(88, 144),
              size=wx.Size(64, 14), style=0)

        self.TCSpec = wx.TextCtrl(id=wxID_FRAMEPROTCSPEC, name=u'TCSpec',
              parent=self.panel_proEditor, pos=wx.Point(160, 136),
              size=wx.Size(416, 22), style=0, value=u'')

        self.TBrand = wx.StaticText(id=wxID_FRAMEPROTBRAND,
              label=u'\u54c1\u724c\uff1a', name=u'TBrand',
              parent=self.panel_proEditor, pos=wx.Point(88, 176),
              size=wx.Size(51, 16), style=0)
        self.TBrand.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))

        self.TCBrand = wx.TextCtrl(id=wxID_FRAMEPROTCBRAND, name=u'TCBrand',
              parent=self.panel_proEditor, pos=wx.Point(160, 176),
              size=wx.Size(112, 22), style=0, value=u'')

        self.TCType = wx.TextCtrl(id=wxID_FRAMEPROTCTYPE, name=u'TCType',
              parent=self.panel_proEditor, pos=wx.Point(440, 96),
              size=wx.Size(100, 22), style=0, value=u'')

        self.staticBox_proSel = wx.StaticBox(id=wxID_FRAMEPROSTATICBOX_PROSEL,
              label=u'\u6240\u9009\u5546\u54c1', name=u'staticBox_proSel',
              parent=self.panel_proList, pos=wx.Point(704, 16),
              size=wx.Size(536, 312), style=0)

        self.listCtrl_proSel = wx.ListCtrl(id=wxID_FRAMEPROLISTCTRL_PROSEL,
              name=u'listCtrl_proSel', parent=self.panel_proList,
              pos=wx.Point(728, 56), size=wx.Size(488, 248),
              style=wx.LC_REPORT)
        self.listCtrl_proSel.SetHelpText(u'')
        self.listCtrl_proSel.SetLabel(u'')
        self.listCtrl_proSel.SetToolTipString(u'')
        self.listCtrl_proSel.Bind(wx.EVT_LEFT_DCLICK,
              self.OnListCtrl_proSelLeftDclick)

        self.btnConfirm = wx.Button(id=wxID_FRAMEPROBTNCONFIRM,
              label=u'\u786e\u5b9a', name=u'btnConfirm',
              parent=self.panel_proList, pos=wx.Point(728, 360),
              size=wx.Size(64, 26), style=0)
        self.btnConfirm.Bind(wx.EVT_BUTTON, self.OnBtnConfirmButton,
              id=wxID_FRAMEPROBTNCONFIRM)

        self.btnAbolish = wx.Button(id=wxID_FRAMEPROBTNABOLISH,
              label=u'\u53d6\u6d88', name=u'btnAbolish',
              parent=self.panel_proList, pos=wx.Point(904, 360),
              size=wx.Size(64, 26), style=0)
        self.btnAbolish.Bind(wx.EVT_BUTTON, self.OnBtnAbolishButton,
              id=wxID_FRAMEPROBTNABOLISH)

        self.btnDel = wx.Button(id=wxID_FRAMEPROBTNDEL, label=u'\u5220\u9664',
              name=u'btnDel', parent=self.panel_proList, pos=wx.Point(816, 360),
              size=wx.Size(64, 26), style=0)
        self.btnDel.Bind(wx.EVT_BUTTON, self.OnBtnDelButton,
              id=wxID_FRAMEPROBTNDEL)

        self.btnSearchCategory = wx.Button(id=wxID_FRAMEPROBTNSEARCHCATEGORY,
              label=u'+', name=u'btnSearchCategory',
              parent=self.panel_proEditor, pos=wx.Point(544, 96),
              size=wx.Size(25, 25), style=0)
        self.btnSearchCategory.Bind(wx.EVT_BUTTON,
              self.OnBtnSearchCategoryButton,
              id=wxID_FRAMEPROBTNSEARCHCATEGORY)

        self.TKeyword = wx.StaticText(id=wxID_FRAMEPROTKEYWORD,
              label=u'\u5173\u952e\u5b57\uff1a', name=u'TKeyword',
              parent=self.panel_proEditor, pos=wx.Point(88, 216),
              size=wx.Size(68, 16), style=0)

        self.tcKeyword = wx.TextCtrl(id=wxID_FRAMEPROTCKEYWORD,
              name=u'tcKeyword', parent=self.panel_proEditor, pos=wx.Point(160,
              208), size=wx.Size(416, 26), style=0, value=u'')

        self.btnSearchKeyword = wx.Button(id=wxID_FRAMEPROBTNSEARCHKEYWORD,
              label=u'+', name=u'btnSearchKeyword', parent=self.panel_proEditor,
              pos=wx.Point(584, 208), size=wx.Size(25, 25), style=0)
        self.btnSearchKeyword.Bind(wx.EVT_BUTTON, self.OnBtnSearchKeywordButton,
              id=wxID_FRAMEPROBTNSEARCHKEYWORD)

        self.notebook1 = wx.Notebook(id=wxID_FRAMEPRONOTEBOOK1,
              name='notebook1', parent=self.panel_proList, pos=wx.Point(8, 8),
              size=wx.Size(656, 576), style=0)

        self.panel1 = wx.Panel(id=wxID_FRAMEPROPANEL1, name='panel1',
              parent=self.notebook1, pos=wx.Point(0, 0), size=wx.Size(648, 547),
              style=wx.TAB_TRAVERSAL)

        self.panel2 = wx.Panel(id=wxID_FRAMEPROPANEL2, name='panel2',
              parent=self.notebook1, pos=wx.Point(0, 0), size=wx.Size(648, 547),
              style=wx.TAB_TRAVERSAL)

        self.TCategory = wx.StaticText(id=wxID_FRAMEPROTCATEGORY,
              label=u'\u5546\u54c1\u7c7b\u522b\uff1a', name=u'TCategory',
              parent=self.panel1, pos=wx.Point(16, 16), size=wx.Size(85, 16),
              style=0)

        self.staticText1 = wx.StaticText(id=wxID_FRAMEPROSTATICTEXT1,
              label=u'\u641c\u7d22\u6807\u7b7e\uff1a', name='staticText1',
              parent=self.panel1, pos=wx.Point(16, 48), size=wx.Size(85, 16),
              style=0)

        self.btnCategory = wx.lib.buttons.GenButton(id=wxID_FRAMEPROBTNCATEGORY,
              label='genButton1', name=u'btnCategory', parent=self.panel1,
              pos=wx.Point(112, 8), size=wx.Size(304, 24), style=0)
        self.btnCategory.Bind(wx.EVT_BUTTON, self.OnBtnCategoryButton,
              id=wxID_FRAMEPROBTNCATEGORY)

        self.btnKeyword = wx.lib.buttons.GenButton(id=wxID_FRAMEPROBTNKEYWORD,
              label='genButton2', name=u'btnKeyword', parent=self.panel1,
              pos=wx.Point(112, 40), size=wx.Size(304, 24), style=0)
        self.btnKeyword.Bind(wx.EVT_BUTTON, self.OnBtnKeywordButton,
              id=wxID_FRAMEPROBTNKEYWORD)

        self.tSearch = wx.StaticText(id=wxID_FRAMEPROTSEARCH,
              label=u'\u641c\u7d22\uff1a', name=u'tSearch', parent=self.panel1,
              pos=wx.Point(16, 80), size=wx.Size(51, 16), style=0)

        self.tcSearch = wx.TextCtrl(id=wxID_FRAMEPROTCSEARCH, name=u'tcSearch',
              parent=self.panel1, pos=wx.Point(112, 72), size=wx.Size(120, 26),
              style=wx.TE_PROCESS_ENTER, value=u'')
        self.tcSearch.Bind(wx.EVT_TEXT_ENTER, self.OnTcSearchTextEnter,
              id=wxID_FRAMEPROTCSEARCH)

        self.btnSearch = wx.Button(id=wxID_FRAMEPROBTNSEARCH,
              label=u'\u641c\u7d22', name=u'btnSearch', parent=self.panel1,
              pos=wx.Point(248, 72), size=wx.Size(93, 26), style=0)
        self.btnSearch.Bind(wx.EVT_BUTTON, self.OnBtnSearchButton,
              id=wxID_FRAMEPROBTNSEARCH)

        self.btnAddLabel = wx.Button(id=wxID_FRAMEPROBTNADDLABEL,
              label=u'\u6dfb\u52a0\u5230\u641c\u7d22\u6807\u7b7e',
              name=u'btnAddLabel', parent=self.panel1, pos=wx.Point(376, 72),
              size=wx.Size(144, 26), style=0)
        self.btnAddLabel.Bind(wx.EVT_BUTTON, self.OnBtnAddLabelButton,
              id=wxID_FRAMEPROBTNADDLABEL)

        self._init_coll_NBProInfo_Pages(self.NBProInfo)
        self._init_coll_notebook1_Pages(self.notebook1)

    def _initGrid(self, grid, row, titles):
        grid.CreateGrid(row, len(titles))
        for i in range(len(titles)):
            grid.SetColLabelValue(i, titles[i])
    
    def initData(self):
        #ID
        self.proId = CDataProduct.newId()
        self.TCID.SetValue(str(self.proId))
        
        #keyword
        #CDataKeyword.refreshDataList() #moved into main 
        self.refreshViewKeyword()
        self.curKeywords = []
        
        #category
        #CDataCategory.refreshDataList() #moved into main
        self.refreshViewCategory()
        self.curCategory = None
        
        #product   
        
        self.cols = ['id','name','categoryId','brand','spec','onUse','unit1','onhand1','defCost1',
                    'defSale1','lastPur1','minPur1','maxPur1']
##        for i in range(len(self.cols)):
##            n = product.CDataProduct.getFieldNo(self.cols[i])
##            cnName = product.CDataProduct.m_fieldCNNames[n]
##            self.listCtrl_pro.InsertColumn(i, cnName)
        
        #移除以下代码，因为替换为自定义MyProductListCtrl
##        CListCtrlAider.initListCtrlCols(self.listCtrl_pro, self.cols, CDataProduct)    
##        #product.CDataProduct.refreshDataList() #moved into main
##        self.refreshViewProductList()
        
    def __init__(self, parent):
        self._init_ctrls(parent)
        
        self.SetSize(Cfg.getDlgAreaSize())
        self.Move(Cfg.getDlgAreaPos())
        
        self.myInit()
##        #产品类型
##        for key in product.specDesc.iterkeys():
##            self.ComboType.Append(key)
        
        
##        #规格表格
##        self.resetGridSpec(self.ComboType.GetValue())
        
        #单位表格
        title_unit = [u'单位', u'关系', u'在手数量', u'预设成本', u'预设售价',
                        u'最近进价', u'最低进价', u'最高进价']
        self._initGrid(self.gridUnit, 3, title_unit)
                
##        #库存表格
##        title_stock = [u'仓库', u'当前', u'最小', u'最小']
##        self._initGrid(self.gridWarehouse, 1, title_stock)

##        self.treeType.AddRoot(u'所有类别')
        
        #商品分类弹出菜单
        self.categoryMenu = wx.Menu()
        categoryMenuList = [u'添加',u'删除',u'重命名']
        for menuItem in categoryMenuList:
            item = self.categoryMenu.Append(-1, menuItem)
            self.Bind(wx.EVT_MENU, self.OnPopupItemSelected, item)
        
        #商品购销列表
        cols = [u'编号', u'名称', u'单位', u'数量', u'单价', u'小计']
        CListCtrlAider.initListCtrlCols(self.listCtrl_proSel, cols)
        
        self.initData()
    
    def myInit(self):
        self.proList = MyProductListCtrl(self.panel1)
        self.proList.SetSize((550,400))
        self.proList.Move((16,100))
        self.proList.Bind(wx.EVT_LEFT_DCLICK, self.OnProListLeftDclick)

        self.proList.refresh()
        #移除以下代码，因为替换为自定义MyProductListCtrl
##        self.listCtrl_pro = wx.ListCtrl(id=wxID_FRAMEPROLISTCTRL_PRO,
##              name=u'listCtrl_pro', parent=self.panel1, pos=wx.Point(40, 96),
##              size=wx.Size(568, 56), style=wx.LC_SINGLE_SEL | wx.LC_REPORT)
##        self.listCtrl_pro.SetToolTipString(u'')
##        self.listCtrl_pro.SetLabel(u'')
##        self.listCtrl_pro.Bind(wx.EVT_LEFT_DCLICK,
##              self.OnListCtrl_proLeftDclick)

##    def resetGridSpec(self, proType):                 
##        #self.gridSpec.ClearGrid()
##        if proType in product.specDesc:
##            if (self.gridSpec.GetNumberRows() != 0):                
##                self.gridSpec.DeleteRows(0, self.gridSpec.GetNumberRows())
##                self.gridSpec.AppendRows(len(product.specDesc[proType]))
##            else:
##                self.gridSpec.CreateGrid(len(product.specDesc[proType]), 1)            
##            
##            for i in range(len(product.specDesc[proType])):
##                self.gridSpec.SetRowLabelValue(i, product.specDesc[proType][i])
##        else:
##            pass
##    
##    def OnComboTypeText(self, event):
##        self.resetGridSpec(self.ComboType.GetValue())

    def OnBtnSaveButton(self, event):
        '''保存产品信息到数据库'''
        #Save the basic Info
        mPro = CDataProduct()
        fields = {}
        
        name = self.TCName.GetValue()
        spec = self.TCSpec.GetValue()
        if (name == '' or spec == ''):
            if (name == '' and spec == ''):
                dlg = wx.MessageDialog(self,
                            u'没有填写商品名称和规格信息，二者必须至少填写一个',
                            u'提示', wx.OK|wx.ICON_ERROR)
                dlg.ShowModal()
                return
            elif (name == ''):
                self.TCName.SetValue(spec)
                dlg = wx.MessageDialog(self, u'没有填写商品名称，自动补填商品规格',
                                        u'提示', wx.OK|wx.ICON_ERROR)
                dlg.ShowModal()
                return
            elif (spec == ''):
                self.TCSpec.SetValue(name)
                dlg = wx.MessageDialog(self, u'没有填写商品规格，自动补填商品名称',
                                        u'提示', wx.OK|wx.ICON_ERROR)
                dlg.ShowModal()
                return
        briefCode = self.TCSimCode.GetValue()
        
##        typeid = self.TCType.GetValue()
##        if (typeid == ''):
##            typeid = None
        if (self.curCategory is None):
            typeid = None
        else:
            typeid = self.curCategory.getFieldVal(index=CDataCategory.COL_ID)
            
        brand = self.TCBrand.GetValue()
        onUse = int(self.CheckOnUse.GetValue())
        memo = self.TCMemo.GetValue()
        
        fields[CDataProduct.COL_ID] = self.proId
        fields[CDataProduct.COL_NAME] = name
        fields[CDataProduct.COL_SPEC] = spec
        fields[CDataProduct.COL_BRIEFCODE] = briefCode
        fields[CDataProduct.COL_CATEGORYID] = typeid
        fields[CDataProduct.COL_BRAND] = brand
        fields[CDataProduct.COL_ONUSE] = onUse
        fields[CDataProduct.COL_MEMO] = memo
        mPro.setMulFieldVal(fields)    

        #设置单位信息
        unitVal = []
        bBlank = False
        for i in range(self.gridUnit.GetNumberRows()):              
            for j in range(self.gridUnit.GetNumberCols()):
                val = self.gridUnit.GetCellValue(i, j)
                if (val == ''):
                    if(j == 0):# None Unit
                        bBlank = True
                    else:
                        val = None
                if (bBlank and val != '' and val is not None):
                    log(DBG, 'i=%d j=%d val=%s', (i,j,val))
                    msg = u'单位设置：第%d行缺失单位名称，请检查输入' %(i+1)
                    dlg = wx.MessageDialog(self, msg,
                                        u'提示', wx.OK|wx.ICON_ERROR)
                    dlg.ShowModal()
                    return
                unitVal.append(val)
                
        if (unitVal[0] == ''):
            dlg = wx.MessageDialog(self, u'单位设置：第1行缺失单位名称，请检查输入',
                                        u'提示', wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        mPro.setUnitData(unitVal) 
        mPro.insertNewData()
        self.refreshViewProductList()
        
        #Set Keyword
        CDataProLabel.delData({CDataProLabel.COL_PROID:self.proId})
        for i in range(len(self.curKeywords)):
            obj = CDataProLabel()
            fields = {CDataProLabel.COL_PROID:self.proId,
                        CDataProLabel.COL_LABELID:self.curKeywords[i].getFieldVal(index=CDataKeyword.COL_ID)}
            obj.setMulFieldVal(fields)
            obj.insertNewData()
##        n = product.CDataProduct.getFieldNo('name')
##        mPro.m_fieldVals[n] = self.TCName.GetValue()
##         
##        n = product.CDataProduct.getFieldNo('briefCode')
##        mPro.m_fieldVals[n] = 
##        
##        n = product.CDataProduct.getFieldNo('typeid')
##        mPro.m_fieldVals[n] = self.TCType.GetValue()
##        if (mPro.m_fieldVals[n] == ''):
##            mPro.m_fieldVals[n] = None
##            
##        n = product.CDataProduct.getFieldNo('spec')
##        mPro.m_fieldVals[n] = self.TCSpec.GetValue()
##        
##        n = product.CDataProduct.getFieldNo('brand')
##        mPro.m_fieldVals[n] = self.TCBrand.GetValue()
##        
##        n = product.CDataProduct.getFieldNo('onUse')
##        mPro.m_fieldVals[n] = int(self.CheckOnUse.GetValue())
##        
##        unitStart = product.CDataProduct.getFieldNo('unit1')    
##        for i in range(self.gridUnit.GetNumberRows()):
##            for j in range(self.gridUnit.GetNumberCols()):
##                n = unitStart + i * 8 + j
##                mPro.m_fieldVals[n] = self.gridUnit.GetCellValue(i, j)
##                if (mPro.m_fieldVals[n] == ''):
##                    mPro.m_fieldVals[n] = None
##                #mPro.unit[i][j] = self.gridUnit.GetCellValue(i, j)
##                #if (mPro.unit[i][j] == ''):
##                    #mPro.unit[i][j] = None
##        
##        n = product.CDataProduct.getFieldNo('memo')
##        mPro.m_fieldVals[n] = self.TCMemo.GetValue()
##        
##        mPro.insertNewData()
##        #product.CDataProduct.refreshDataList()
##        self.refreshViewProductList()
##        #self.Show(False)
        
    def refreshViewProductList(self):
        CListCtrlAider.refreshListCtrlData(self.listCtrl_pro, self.cols, CDataProduct)   
##        self.listCtrl_pro.DeleteAllItems()      
##        for obj in product.CDataProduct.m_dataList:
##            #n = product.CDataProduct.getFieldNo(self.cols[0])
##            #row = self.listCtrl_pro.InsertStringItem(row, (obj.m_fieldVals[n]))
##            row = self.listCtrl_pro.InsertStringItem(sys.maxint, '')
##            for i in range(len(self.cols)):
##                n = product.CDataProduct.getFieldNo(self.cols[i])
##                val = obj.m_fieldVals[n]            
##                if (val == None):
##                    val = ''
##                if (type(val) != str and type(val) != unicode):
##                    val = str(val)
##                #print type(val)
##                self.listCtrl_pro.SetStringItem(row, i, val)
        
    def OnBtnCancelButton(self, event):
        self.Show(False)

    def OnFrameProClose(self, event):
        self.Show(False)
        self.GetParent().Show()

    def OnTreeTypePopup(self, event):
        '''商品分类右键弹出菜单处理'''
##        print u'popup'
        if self.treeType.GetSelection().IsOk():
            pos = self.panel_proList.ScreenToClient(event.GetPosition())
            self.panel_proList.PopupMenu(self.categoryMenu, pos)
    
    def OnTreeTypeTreeItemRightClick(self, event):
##        print u'RightClick'
##        print self.treeType.GetItemText(event.GetItem())
        self.treeType.SelectItem(event.GetItem())
                
    def OnPopupItemSelected(self, event):
        '''商品类别菜单'''
        event.Skip()
        
        item = self.categoryMenu.FindItemById(event.GetId())
        
        print item.GetText()
        if (item.GetText() == u'添加'):
            parentId = self.treeType.GetSelection()
            parent = self.treeType.GetItemText(parentId)
            msg = u'为<%s>添加新的子类别：' %(parent)
            self.dlg = wx.TextEntryDialog(self, msg, u'新建商品类别','')
            if self.dlg.ShowModal() == wx.ID_OK:
                name = self.dlg.GetValue()
                newCategory = product.CDataCategory()
                newCategory.m_fieldVals[product.CDataCategory.getFieldNo(u'name')] = name
                newCategory.m_fieldVals[product.CDataCategory.getFieldNo(u'parentId')] = parent
                newCategory.insertNewData()
                id = self.treeType.AppendItem(parentId, name)
                #product.CDataCategory.refreshDataList()
                #self.refreshViewCategory()
                self.treeType.SelectItem(id)
                #self.treeType.Expand(self.treeType.GetSelection())                
        elif (item.GetText() == u'删除'):
            pass
        elif(item.GetText() == u'重命名'):
            pass
        else:
            print u'Error'
            return -1
    
    def refreshViewCategory(self): 
        pass   
##        ready = []
##        pend = []
##        self.treeType.DeleteAllItems()
##        
##        for obj in product.CDataCategory.m_dataList:
##            parent = obj.m_fieldVals[product.CDataCategory.getFieldNo(u'parentId')]
##            name = obj.m_fieldVals[product.CDataCategory.getFieldNo(u'name')]
####            print name
####            print parent
##            if (parent == None):
##                rootId = self.treeType.AddRoot(name)
##                #dict[name] = rootId
##
##                ready.append([rootId, name])
##            else:
##                pend.append([name, parent])
####                if parent in dict.keys():
####                    parentId = dict[parent]
####                    self.treeType.AppendItem(parentId, name)
####                    ready.append(item[0], data[0])
####                else:
####                    #print u'[ERROR]Category:parent behinds child in DB'
####                    pend.append([name, parent])
####                    #dictPend[parent] = name
##        #print len(ready)
##        #print len(pend)             
##        for readyData in ready:
##            #print 'p:%s' %(readyData[1])
##            for pendData in pend:
##                #print 'c:%s %s' %(pendData[0], pendData[1])
##                if (readyData[1] == pendData[1]):
##                    #print 'add %s' %pendData[0]
##                    id = self.treeType.AppendItem(readyData[0], pendData[0])
##                    ready.append([id, pendData[0]])
##                    #pend.remove(pendData) #iterator BUG          
##        if len(ready) != len(product.CDataCategory.m_dataList):
##            print u'[ERROR]Category'
##            
##        self.treeType.Expand(rootId)
                    
    def OnBtnAddKeywordButton(self, event):
        dlg = wx.TextEntryDialog(self, u'输入新的商品关键字：', u'新建商品关键字','')
        if dlg.ShowModal() == wx.ID_OK:    
            newKeyword = product.CDataKeyword()
            newKeyword.m_fieldVals[product.CDataKeyword.getFieldNo(u'name')] = dlg.GetValue()
            newKeyword.insertNewData()
            product.CDataKeyword.refreshDataList()
            self.refreshViewKeyword()
   
    def refreshViewKeyword(self):
        pass    
##        choices = []
##        for obj in product.CDataKeyword.m_dataList:
##            choices.append(obj.m_fieldVals[product.CDataKeyword.getFieldNo(u'name')])                    
##        self.listBox_Keyword.Set(choices)

    

    
    STATE_CX = 0
    STATE_XS = 1
    STATE_CG = 2
    def setShowState(self, state):
        self.bConfirm = False
        
        if (state == self.STATE_XS or state == self.STATE_CG):
            self.staticBox_proSel.Show()
            self.listCtrl_proSel.Show()
            self.btnConfirm.Show()
            self.btnDel.Show()
            self.btnAbolish.Show()   
            
            self.listCtrl_proSel.DeleteAllItems()
            self.state = state
        elif (state == self.STATE_CX):
            self.staticBox_proSel.Hide()
            self.listCtrl_proSel.Hide()
            self.btnConfirm.Hide()
            self.btnDel.Hide()
            self.btnAbolish.Hide()
            
            self.state = state
        else:
            print '[Error]UnKown state: \'%s\'' %(state)
            
    def OnProListLeftDclick(self, event):
        '''左键双击产品列表'''
        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if (item == -1):
            return
        fields = {'id':self.proList.GetItemText(item)}

        print fields
        obj = CDataProduct.getData(fields)
        if (obj == None):
            print '[Error]unknown product: %s' %(fields)
        else:
            if (self.state == self.STATE_XS or self.state == self.STATE_CG):
                dlg = DlgProGX(self)
                dlg.setData(obj)
##                ret = dlg.ShowModal()
##                print ret
##                print dlg.GetReturnCode()
                if (dlg.ShowModal() == wx.ID_OK):
##                    print 'OK'
                    dataList = [str(obj.m_fieldVals[CDataProduct.getFieldNo(u'id')]),
                                obj.m_fieldVals[CDataProduct.getFieldNo(u'name')],
                                dlg.unit, str(dlg.cnt), str(dlg.price), str(dlg.cnt*dlg.price)]
                    CListCtrlAider.appendItem(self.listCtrl_proSel, dataList)
        event.Skip()
    
        
                    
    def OnListCtrl_proSelLeftDclick(self, event):
        '''左键双击选中产品列表'''
        item = self.listCtrl_proSel.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        fields = {'id':self.listCtrl_proSel.GetItemText(item)}

        obj = CDataProduct.getData(fields)
        if (obj is None):
            print '[Error]unknown product: %s' %(fields)
            return
                    
        dlg = DlgProGX(self)
        unit = self.listCtrl_proSel.GetItem(item, 2).GetText()
        cnt = float(self.listCtrl_proSel.GetItem(item, 3).GetText())
        price = float(self.listCtrl_proSel.GetItem(item, 4).GetText())
        print '%s %s %s' %(unit, cnt, price)
        dlg.setData(obj, unit=unit, cnt=cnt, price=price)
      
        if (dlg.ShowModal() == wx.ID_OK):
##                dataList = [str(obj.m_fieldVals[CDataProduct.getFieldNo(u'id')]),
##                            obj.m_fieldVals[CDataProduct.getFieldNo(u'name')],
##                            dlg.unit, str(dlg.cnt), str(dlg.price), str(dlg.cnt*dlg.price)]
##                CListCtrlAider.appendItem(self.listCtrl_proSel, dataList)
            self.listCtrl_proSel.SetStringItem(item, 2, dlg.unit)
            self.listCtrl_proSel.SetStringItem(item, 3, str(dlg.cnt))
            self.listCtrl_proSel.SetStringItem(item, 4, str(dlg.price))
            self.listCtrl_proSel.SetStringItem(item, 5, str(dlg.cnt*dlg.price))                       
        
            
    def OnBtnConfirmButton(self, event):
        self.GetParent().fSO.setGridData(self.listCtrl_proSel)
        self.Show(False)
        event.Skip()

    def OnBtnAbolishButton(self, event):
        #self.Close()
        self.Show(False)
        event.Skip()
        
    def OnBtnDelButton(self, event):
        item = self.listCtrl_proSel.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        self.listCtrl_proSel.DeleteItem(item)
        #self.Show(False)
        event.Skip()

    def OnFrameProPaint(self, event):
        print 'OnFrameProPaint'
        event.Skip()

    def OnBtnSearchCategoryButton(self, event):
##        dlg = PopupWinCategory(self)
##        btn = event.GetEventObject()
##        pos = btn.ClientToScreen( (0,0) )
##        sz =  btn.GetSize()
##        dlg.Position(pos, (0, sz[1]))
##        dlg.Show()
        dlg = DlgCategory(self)
        if (self.curCategory is not None):
            dlg.setSelection(self.curCategory)
        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x-dlgSize[0]/2, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return
        
        self.curCategory = dlg.categorySel
        self.TCType.SetValue(self.curCategory.getFieldVal(index=CDataCategory.COL_NAME))
        

    def OnBtnSearchKeywordButton(self, event):
        
        dlg = DlgKeyword(self)
        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x-dlgSize[0]/2, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return

        self.curKeywords = dlg.keywordSel
        str = ''
        for obj in self.curKeywords:
            str += '%s  ' %obj.getFieldVal(index=CDataKeyword.COL_NAME)
        self.tcKeyword.SetValue(str)

    def OnBtnAddProButton(self, event):
        dlg = DlgEditPro(self)
        dlg.ShowModal()

    def OnBtnCategoryButton(self, event):
        
        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()
        
        dlg = DlgCategory.create(self)
        if (self.curCategory is not None):
            dlg.setSelection(self.curCategory)
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return

        self.curCategory = dlg.categorySel
        btn.SetLabel(self.curCategory.getFieldVal(index=CDataCategory.COL_NAME))
        btn.SetSize(btn.GetBestSize())
        self.refreshProductList()
        
    def OnBtnKeywordButton(self, event):
        
        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()
        
        dlg = DlgKeyword.create(self)
        dlg.setData(self.curKeywords)
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return
        
        

        self.curKeywords = dlg.keywordSel
        str = ''
        for obj in self.curKeywords:
            str += '%s  ' %obj.getFieldVal(index=CDataKeyword.COL_NAME)
        btn.SetLabel(str)
        btn.SetSize(btn.GetBestSize())
        self.refreshProductList()

    def refreshProductList(self):
        '''根据搜索条件（类别、关键字），重设产品列表'''
        categoryIds = []
        if (self.curCategory is not None):
            categoryId = self.curCategory.getFieldVal(index=CDataCategory.COL_ID)
            categoryIds = CDataCategory.getChildId(categoryId)
        
        keywordIds = []
        for obj in self.curKeywords:
            keywordIds.append(obj.getFieldVal(index=CDataKeyword.COL_ID))
        
        #重设产品
        self.proList.setFilter(keywordIds, categoryIds)
        self.proList.refresh()

    def refreshList(self, val):
        #print val
        if (val == ''):
            self.proList.refresh()
        else:
            self.proList.refreshView(val)
        
    def OnBtnSearchButton(self, event):
        #print 'OnBtnSearchButton'
        self.refreshList(self.tcSearch.GetValue())

    def OnTcSearchTextEnter(self, event):
        #print 'OnTcSearchTextEnter'
 
        self.btnSearch.SetFocus()
        self.refreshList(self.tcSearch.GetValue())

    def OnBtnAddLabelButton(self, event):
        '''把搜索内容设置为label，并关联到列表中的显示项目'''
        if (self.tcSearch.GetValue() == ''):
            return
        
        labelId = CDataKeyword.insertNew(self.tcSearch.GetValue())
        if (labelId == -1):
            # check if it is insert already
            label = CDataKeyword.find(self.tcSearch.GetValue())
            if (label is None):
                return
            else:
                labelId = label.getValue(CDataKeyword.COL_ID)
        
        for row in range(self.proList.GetItemCount()):
            obj = CDataProLabel()
            fields = {CDataProLabel.COL_PROID:self.proList.getProId(row),
                        CDataProLabel.COL_LABELID:labelId}
            obj.setMulFieldVal(fields)
            obj.insert()
